<?php

declare(strict_types=1);
/**
 * 创建人 : Forpastime
 *
 * @link     http://hypercmf.com
 * @document https://hyperf.wiki
 * @contact  forpastime@qq.com
 * @git  https://gitee.com/hypercmf/hypercmf1.0.git
 */
namespace App\Listener;

use App\Event\SmsSend;
use App\Event\UserRegistered;
use Hyperf\Event\Annotation\Listener;
use Hyperf\Event\Contract\ListenerInterface;
use Hyperf\Redis\RedisFactory;
use Hyperf\Utils\ApplicationContext;
use Psr\Container\ContainerInterface;

/**
 * @Listener
 */
#[Listener]
class SendSmsListener implements ListenerInterface
{
    /**
     * @var ContainerInterface
     */
    private $container;

    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
    }

    public function listen(): array
    {
        return [
            UserRegistered::class,
            SmsSend::class,
        ];
    }

    /**
     * @param SmsSend $event
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    public function process(object $event)
    {
        if ($event instanceof UserRegistered) {
            // 如果是注册成功过后短信通知
            echo 'UserRegistered Notice';
            // 这里写实际发送模板短信的第三方的代码 TODO 这里我们存入redis表示发送
            $container = ApplicationContext::getContainer();
            $redis = $container->get(RedisFactory::class)->get('db1');
            $redis->setex('regist_notice', 600, $event->mobile . ',恭喜您注册成功！');
            $event->hasSend = true;

        // }else if(get_class($event).$event instanceof SmsSend){
        } elseif ($event instanceof SmsSend) {
            // 如果是短信验证码发送
            $container = ApplicationContext::getContainer();
            $redis = $container->get(RedisFactory::class)->get('db1');

            $redis->setex('sms:' . $event->type . ':' . $event->mobile, 15 * 60, $event->code);

            // 这里写实际发送短信的第三方的代码 TODO

            $event->hasSend = true;
        }
    }
}
